import React, { useRef, useEffect, useState } from 'react';
import { Button, Input, Space, Table } from 'antd';
import { TempImportModal, HcpTableTooltip, useModelAssociateType, Authorized } from '@/components';
import cmdbres from '@/data/cmdbres';
import request from '@/utils/request';
import permission from '@/config/permission';
import CreateRelation from './createRelation';
import EditRelation from './editRelation';
import DeleteRelation from './deleteRelation';
import DetailModal from './detail';

const ModelRelation = ({ history, match, moduleId, moduleInfo }) => {
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState([]);
    const [showCreateRelation, setShowCreateRelation] = useState(false);
    const [showEditRelation, setShowEditRelation] = useState(false);
    const [showDeleteRelation, setShowDeleteRelation] = useState(false);
    const [showImportModal, setShowImportModal] = useState(false);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [{ associateType }] = useModelAssociateType();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const queryModelAssociate = async (params = { current: 1, pageSize: 10 }) => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryModelAssociateList(moduleId),
                data: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    sort: {
                        create_time: 'DESC',
                    },
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                res.data.map((item) => (item.key = item.id));
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        if (moduleId) queryModelAssociate();
    }, [moduleId]);

    const columns = [
        {
            title: '模型关联ID',
            dataIndex: 'moduleAssociateCode',
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => (
                <HcpTableTooltip
                    label="moduleAssociateCode"
                    showValue={text}
                    onClick={() => {
                        setRow(record);
                        setShowDetailModal(true);
                    }}
                />
            ),
        },
        {
            title: '模型关联名称',
            dataIndex: 'moduleAssociateName',
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: '目标模型',
            dataIndex: 'destModuleName',
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: '关联类型',
            dataIndex: 'associateType',
            isShow: true,
            width: 120,
            render: (text, record, index) => {
                return `${text}(${associateType?.[text] ?? '-'})`;
            },
        },
        {
            title: '源-目标约束',
            dataIndex: 'mapping',
            isShow: true,
            width: 120,
        },
        {
            title: '操作',
            fixed: 'right',
            width: 110,
            woIsSystem: 1,
            woIsHidden: 1,
            render: (text, record, index) => {
                return (
                    <Space key={record.cm_unid}>
                        <Authorized authority={permission.modelRelation_edit} noMatch={null}>
                            <a
                                onClick={() => {
                                    setRow(record);
                                    setShowEditRelation(true);
                                }}
                            >
                                编辑
                            </a>
                        </Authorized>
                        <Authorized authority={permission.modelRelation_delete} noMatch={null}>
                            <a
                                onClick={() => {
                                    setRow(record);
                                    setShowDeleteRelation(true);
                                }}
                            >
                                删除
                            </a>
                        </Authorized>
                    </Space>
                );
            },
        },
    ];

    const handleTableChange = (e) => {
        getTableData(e);
    };

    return (
        <div style={{ backgroundColor: '#fff', padding: '0 20px' }}>
            <div style={{ display: 'inline-block', width: '50%' }}>
                <section style={{ padding: '5px 10px 20px 0' }}>
                    <Space>
                        {/* <Button type="primary" onClick={() => {setShowImportModal(true);}}>
                            导入
                        </Button> */}
                        <Authorized authority={permission.modelRelation_add} noMatch={null}>
                            <Button
                                type="primary"
                                onClick={() => {
                                    setShowCreateRelation(true);
                                }}
                            >
                                新建模型关联
                            </Button>
                        </Authorized>
                        <Button type="primary" onClick={queryModelAssociate}>
                            刷新
                        </Button>
                    </Space>
                </section>
            </div>
            <p>模型关联 | {pagination.total}个</p>
            <Table
                columns={columns}
                loading={loading}
                dataSource={tableData}
                scroll={{ x: '100%' }}
                pagination={{
                    showSizeChanger: true,
                    showQuickJumper: {
                        goButton: <Button style={{ margin: '0 10px' }}>确定</Button>,
                    },
                    ...pagination,
                }}
                onChange={handleTableChange}
                hideSetting
            />
            {showCreateRelation && (
                <CreateRelation
                    onCreateFinish={() => {
                        queryModelAssociate();
                    }}
                    visible={showCreateRelation}
                    setVisible={setShowCreateRelation}
                    moduleInfo={moduleInfo}
                />
            )}
            {showEditRelation && (
                <EditRelation
                    onCreateFinish={() => {
                        queryModelAssociate();
                    }}
                    visible={showEditRelation}
                    setVisible={setShowEditRelation}
                    info={row}
                    moduleInfo={moduleInfo}
                />
            )}
            <DeleteRelation
                onDeleteFinish={queryModelAssociate}
                visible={showDeleteRelation}
                setVisible={setShowDeleteRelation}
                info={row}
            />
            <TempImportModal
                visible={showImportModal}
                setVisible={setShowImportModal}
                onImportFinish={() => queryModelAssociate()}
                downloadApi="模型关系.xlsx" // 下载模板
                downloadURL={'/module/export/export-associate-excel'} // 下载地址
                importApi={cmdbres.importModelAssociate} // 导入地址
            />
            <DetailModal visible={showDetailModal} setVisible={setShowDetailModal} info={row} />
        </div>
    );
};

export default ModelRelation;
